Page({
  data: {
    email: '',
    token: '',
    newPassword: '',
    confirmPassword: '',
    step: 1 // 1: 请求重置邮件, 2: 验证令牌并设置新密码
  },

  onInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [field]: e.detail.value
    });
  },

  async requestResetEmail() {
    const { email } = this.data;
    if (!email) {
      wx.showToast({
        title: '请输入邮箱',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await wx.request({
        url: `${getApp().globalData.baseUrl}/api/password/forgot`,
        method: 'POST',
        data: { email },
        header: {
          'Content-Type': 'application/json'
        }
      });

      if (res.statusCode === 200 && res.data.success) {
        wx.showToast({
          title: '重置邮件已发送，请检查您的邮箱',
          icon: 'success',
          duration: 3000
        });
        this.setData({ step: 2 });
      } else {
        wx.showToast({
          title: res.data.message || '发送失败',
          icon: 'none'
        });
      }
    } catch (err) {
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
      console.error('请求重置邮件失败:', err);
    }
  },

  async resetPassword() {
    const { token, newPassword, confirmPassword } = this.data;

    if (!token || !newPassword || !confirmPassword) {
      wx.showToast({
        title: '请填写所有字段',
        icon: 'none'
      });
      return;
    }
    if (newPassword !== confirmPassword) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await wx.request({
        url: `${getApp().globalData.baseUrl}/api/password/reset-by-token?token=${token}`,
        method: 'POST',
        data: { newPassword },
        header: {
          'Content-Type': 'application/json'
        }
      });

      if (res.statusCode === 200 && res.data.success) {
        wx.showToast({
          title: '密码重置成功，请重新登录',
          icon: 'success',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              wx.redirectTo({ url: '/pages/login/login' });
            }, 2000);
          }
        });
      } else {
        wx.showToast({
          title: res.data.message || '重置失败',
          icon: 'none'
        });
      }
    } catch (err) {
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
      console.error('重置密码失败:', err);
    }
  }
}); 